package com.ywjh.inter.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import com.ywjh.inter.entity.AlarmDataEntity;

public class AlarmDataDAO {
	public boolean insert(Connection conn, AlarmDataEntity dataEntity) throws SQLException {
		boolean b = false;
		PreparedStatement ps = conn.prepareStatement(
				"insert into alarm_data(user_id,data_id,data_type,status,add_time,alarm_type) values(?,?,?,?,?,?)");
		ps.setInt(1, dataEntity.getUser_id());
		ps.setInt(2, dataEntity.getData_id());
		ps.setString(3, dataEntity.getData_type());
		ps.setInt(4, dataEntity.getStatus());
		ps.setTimestamp(5, dataEntity.getAdd_time());
		ps.setString(6, dataEntity.getAlarm_type());
		if (ps.executeUpdate() > 0) {
			b = true;
		}
		return b;
	}

	public List<AlarmDataEntity> listByUserId(Connection conn, int user_id, int page, int num) throws SQLException {
		List<AlarmDataEntity> list = new LinkedList<AlarmDataEntity>();
		PreparedStatement ps = conn
				.prepareStatement("select * from alarm_data where user_id=? order by add_time desc limit ?,? ");

		ps.setInt(1, user_id);
		ps.setInt(2, page * num);
		ps.setInt(3, num);
		ResultSet rs = ps.executeQuery();
		while (rs.next()) {
			AlarmDataEntity ae = fill(rs);
			list.add(ae);
		}
		return list;
	}

	private AlarmDataEntity fill(ResultSet rs) throws SQLException {
		AlarmDataEntity ae=new AlarmDataEntity();
		ae.setAdd_time(rs.getTimestamp("add_time"));
		ae.setAlarm_type(rs.getString("alarm_type"));
		ae.setData_id(rs.getInt("data_id"));
		ae.setData_type(rs.getString("data_type"));
		ae.setId(rs.getInt("id"));
		ae.setStatus(rs.getInt("status"));
		ae.setUser_id(rs.getInt("user_id"));
		return ae;
	}

	public List<AlarmDataEntity> listByUsersId(Connection conn, String array, int page, int num) throws SQLException {
		List<AlarmDataEntity> list = new LinkedList<AlarmDataEntity>();
		if(array==null||"".equals(array)) {
			return list;
		}
		PreparedStatement ps = conn.prepareStatement(
				"select * from alarm_data where user_id in (" + array + ") order by add_time desc limit ?,? ");
		ps.setInt(1, page * num);
		ps.setInt(2, num);
		ResultSet rs = ps.executeQuery();
		while (rs.next()) {
			AlarmDataEntity ae = fill(rs);
			list.add(ae);
		}
		return list;
	}
}
